package plp.functional2.concurrency;

import java.util.ArrayList;
import java.util.List;

import plp.expressions2.expression.Expressao;
import plp.expressions2.expression.Id;
import plp.functional2.primitive.Message;

/**
 * Keeps all the messages exchanged between process.
 * @author Airton
 *
 */
public class MailBox {

	private static List<Message> messages = new ArrayList<Message>();
	private static MailBox mailBox = null;
	
	private MailBox() {
		super();
	}

	public static synchronized MailBox getInstance(){
		if (mailBox == null) {
			mailBox = new MailBox();		
			return mailBox;
		}else{
			return mailBox;
		}
	}
	
	public void setMessages(List<Message> newMessages) {
		messages = newMessages;
	}
	
	public void addMessage(Message message){
		messages.add(message);
		System.out.println("### MsgSize = "+ messages.size() + " ###");
	}

	public synchronized Message getMessage(Id processReceiver, List<Id> pattern){
		Message messageToRemove = null; 
		for (Message message: messages) {
			List<Expressao> msgPattern = message.getPattern();
			if (message.getIdProcessReceiver().equals(processReceiver) 
					&& msgPattern.size() == pattern.size()
					&& msgPattern.get(0).equals(pattern.get(0))) {
				messageToRemove = message;
				messages.remove(messageToRemove);
				break;
			}
		}		
		
		return messageToRemove;
	}
}
